package com.jan.activemq01.test;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test;

public class ActiveMqReciverTest01 {
	@Test
	public void test01() throws JMSException{
		//ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("user", "123456", ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://106.15.92.48:61616");
		Connection con = factory.createConnection();
		con.start();
		//true表示开启事务
		Session session = con.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
		Queue que = session.createQueue("bbbb");
		MessageConsumer consumer = session.createConsumer(que);
		
		while(true){
			TextMessage receive = (TextMessage) consumer.receive();
			String msg=receive.getText();
			session.commit();
			System.out.println(msg);
		}
	}
	
	@Test
	public void test2() throws JMSException{
		//topic订阅
		//ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("user", "123456", ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://106.15.92.48:61616");
		Connection con = factory.createConnection();
		con.start();
		Session session = con.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
		Topic top = session.createTopic("top1");
		MessageConsumer consumer = session.createConsumer(top);
		
		while(true){
			TextMessage receive = (TextMessage) consumer.receive();
			String msg=receive.getText();
			System.out.println(msg);
		}
	}
	
	@Test
	public void test3() throws JMSException{
		//持久化topic消费
		//ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("user", "123456", "tcp://localhost:61616");
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://106.15.92.48:61616");
		Connection con = factory.createConnection();
		con.setClientID("cc2");
		
		Session session = con.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
		Topic top = session.createTopic("top1");
		TopicSubscriber ts = session.createDurableSubscriber(top, "T1");
		con.start();
		
		while(true){
			Message receive = ts.receive();
			TextMessage message=(TextMessage) receive;
			System.out.println(message.getText());
		}
	}
}	
